'use strict';
let {src, dest , watch, series} = require('gulp');
let devUrl = "./src"//定义开发路径
// let cssnano = require("gulp-cssnano");//css打包压缩
let gulp = require('gulp');//引入gulp
//引入sass
let sass = require('gulp-sass');//引用sasspipe
sass.compiler = require('node-sass');
let autoprefixer = require("gulp-autoprefixer");
let browserSync = require('browser-sync').create();
let reload = browserSync.reload;//reload重载
const babel = require('gulp-babel');//ES5=>ES6，引用babel转js
let uglify = require('gulp-uglify');//js压缩
const imagemin = require('gulp-imagemin');
//html路径替换
// let cheerio = require("gulp-cheerio");
function devSass() {
  return gulp.src(devUrl + '/scss/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(devUrl + '/css'))
	.pipe(autoprefixer({
			//是否美化
			cascade: false
        }))
	.pipe(reload({stream:true}));
}
//压缩图片
function miniImg(){
	return src(devUrl + '/images/*')
	.pipe(imagemin())
    .pipe(dest('dist/images'))

	
}

//打包压缩代码
function minCss(){
	return src(devUrl + '/css/**/*.css')
	.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
	.pipe(dest('dist/css'))
} 
//转es5 \并压缩js
function minJs(){
	return src(devUrl + '/js/**/*.js')
	 .pipe(babel({
            presets: ['@babel/env']
        }))
	.pipe(uglify({
		// 是否忽略console
		compress:{
			drop_console: true
		}
	}))	
	.pipe(dest('dist/js'))
}

// 静态服务器
function browserync() {
    browserSync.init({
        server: {
			// 对应监听根目录
            baseDir: "./src"
			},
			port: 2626
        })
	// watch(devUrl + '/css/*',reload);
	watch(devUrl + '/css/**/*.css').on("change", reload);
	watch(devUrl + '/js/**/*.js').on("change", reload);
	watch(devUrl + '/*.html').on("change", reload);
	// 监听ss
	watch(devUrl + '/scss/**/*.scss',devSass);
	// watch(devUrl + '/**/*',reload);
};
function copyHtml(){
	return src(devUrl + '*.html')
	.pipe(dest('dist/'))
}
// function copyFont(){
// 	return src(devUrl + '/font/*')
// 	.pipe(dest('dist/font/'))
// }
// let copyTask = parallel(copyHtml,copyFont);


//输出sass任务
exports.devSass = devSass;
// 输出浏览器任外务
exports.dev = browserync;
//定义打包任务
exports.build = series(minCss,minJs,miniImg,copyHtml);